#define _CRT_SECURE_NO_WARNINGS

#include <algorithm>
#include <string>
#include "decoder.h"
#include "encoder.h"

using namespace std;

int main(int argc, char **argv)
{
    char *file_name;
    string dest;
    byte_t buffer[BLOCK_SIZE] = {0};
    int frequency[ASCII_MAXSIZE] = {0};
    int option = 0;
    for (int i = 1; i < argc; i++) {
        char *arg = argv[i];

        if (*arg == '-') {
            char *poption = arg + 1;
            while (char cop = *poption++) {
                switch (cop) {
                    case 'e':
                        option = ENCODING_OPTION;
                        if (dest.empty())
                            dest = "encode.txt"; // 默认
                        break;
                    case 'd':
                        option = DECODING_OPTION;
                        if (dest.empty())
                            dest = "decode.txt"; // 默认
                        break;
                    case 'o':
                        if (++i < argc)
                            dest = argv[i];
                        break;
                    default:;
                }
            }
        } else {
            file_name = arg;
        }
    }

    FILE *fp = fopen(file_name, "r");
    if (option == ENCODING_OPTION) {
        FILE *fp_out = fopen(dest.begin().base(), "w");
        while (fread(buffer, 1, 1, fp) != 0)
            frequency[*buffer]++;

        rewind(fp);
        string EncodingList[ASCII_MAXSIZE];
        makeEncodingList(frequency, EncodingList);
        size_t read_count;
        while ((read_count = fread(buffer, 1, BLOCK_SIZE, fp)) != 0)
            Encoding(buffer, read_count, EncodingList, fp_out);
    } else {
        Decoding(fp, dest);
    }
    return 0;
}
